<template>
  <!-- 馆客多
网址 room.yunvip123.cn
账号 19308612125
密码 123456 -->
  <div class="list-common-table">
    <div class="today-use-count" v-if="todaySummaryData">
      <p style="margin-right: 50px">
        <span>当日晨练消费人次： {{ todaySummaryData.forenoonConsumer }}</span>
        <span style="margin-left: 10px; margin-right: 50px; cursor: pointer" @click="go2CardTypeDetail(1)"
          >查看详情<chevron-right-double-icon size="20"
        /></span>
        <span>晨练会员剩余总划卡次数： {{ todaySummaryData.forenoonRemainderCount }}</span>
      </p>
      <p style="margin-right: 50px">
        <span>当日午场消费人次： {{ todaySummaryData.afternoonConsumer }}</span>
        <span style="margin-left: 10px; margin-right: 50px; cursor: pointer" @click="go2CardTypeDetail(2)"
          >查看详情<chevron-right-double-icon size="20"
        /></span>
        <span>午场会员剩余总划卡次数： {{ todaySummaryData.afternoonRemainderCount }}</span>
      </p>
      <p style="margin-right: 50px">
        <span>当日晚场消费人次： {{ todaySummaryData.nightConsumer }}</span>
        <span style="margin-left: 10px; margin-right: 50px; cursor: pointer" @click="go2CardTypeDetail(3)"
          >查看详情<chevron-right-double-icon size="20"
        /></span>
        <span>晚场会员剩余总划卡次数： {{ todaySummaryData.nightRemainderCount }}</span>
      </p>
    </div>
    <div class="user-tabs">
      <t-tabs v-model="sessionType" :default-value="1" @change="onSessionTypeChanged">
        <t-tab-panel :value="1" label="晨练"> </t-tab-panel>
        <t-tab-panel :value="2" label="午场"> </t-tab-panel>
        <t-tab-panel :value="3" label="晚场"> </t-tab-panel>
      </t-tabs>
      <div class="right-handlers-container">
        <t-button theme="primary" @click="handleClickAddUser">
          <template #icon>
            <add-icon />
          </template>
          {{ `新增${sessionType === 1 ? '晨练' : sessionType === 2 ? '午场' : '晚场'}会员卡` }}
        </t-button>
        <t-button theme="primary" variant="outline" @click="handleClickAddTempUser">
          <template #icon>
            <add-icon />
          </template>
          {{ `新增${sessionType === 1 ? '晨练' : sessionType === 2 ? '午场' : '晚场'}临时卡` }}
        </t-button>
        <t-button variant="base" theme="default" @click="showImportDialog = true">导入</t-button>
        <t-button variant="base" theme="default" @click="exportHandleClick">导出</t-button>
      </div>
    </div>
    <t-form ref="form" :data="formData" :label-width="0" colon @reset="onReset" @submit="onSubmit">
      <t-row>
        <t-col :span="12">
          <t-row :gutter="[15, 15]">
            <t-col :span="2">
              <t-form-item name="userName">
                <t-input
                  v-model="formData.userName"
                  class="form-item-content"
                  type="search"
                  :placeholder="$t('pages.memberBase.memberBaseSearch.memberNamePlaceholder')"
                  :style="{ minWidth: '120px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :span="2">
              <t-form-item name="mobilePhone">
                <t-input
                  v-model="formData.mobilePhone"
                  class="form-item-content"
                  :placeholder="$t('pages.memberBase.memberBaseSearch.memberPhonePlaceholder')"
                  :style="{ minWidth: '120px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :span="2">
              <t-form-item name="gtConsumerCount">
                <t-select
                  v-model="formData.gtConsumerCount"
                  class="form-item-content"
                  :options="USECOUNT_STATUS_OPTIONS"
                  :placeholder="$t('pages.memberBase.memberBaseSearch.useCountPlaceholder')"
                  clearable
                  :style="{ minWidth: '120px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :span="2">
              <t-form-item name="gtConsumerCount">
                <t-select
                  v-model="formData.level"
                  class="form-item-content"
                  :options="USERLEVEL_OPTIONS"
                  :style="{ minWidth: '120px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :span="2">
              <t-form-item name="status">
                <t-select
                  v-model="formData.todayConsumer"
                  class="form-item-content"
                  :options="TODAYDEDUCTION_STATUS_OPTIONS"
                  :placeholder="$t('pages.memberBase.memberBaseSearch.todayDeductionPlaceholder')"
                  clearable
                  :style="{ minWidth: '120px' }"
                />
              </t-form-item>
            </t-col>
            <t-col :span="2" class="operation-container">
              <t-button theme="primary" type="submit" :style="{ marginLeft: 'var(--td-comp-margin-s)' }">
                {{ $t('components.commonTable.query') }}
              </t-button>
              <t-button type="reset" variant="base" theme="default">
                {{ $t('components.commonTable.reset') }}
              </t-button>
            </t-col>
          </t-row>
        </t-col>
      </t-row>
    </t-form>

    <div class="table-container">
      <t-table
        :data="data"
        :columns="COLUMNS"
        :row-key="rowKey"
        :vertical-align="verticalAlign"
        :pagination="pagination"
        :loading="dataLoading"
        :header-affixed-top="headerAffixedTop"
        :stripe="true"
        @page-change="rehandlePageChange"
        @change="rehandleChange"
      >
        <template #userName="{ row }">
          <span v-if="row.level === 0" style="color: red">{{ row.userName }}</span>
          <span v-if="row.level === 1">{{ row.userName }}</span>
          <span v-if="row.level === 2" style="color: green">{{ row.userName }}</span>
        </template>
        <template #remainingNum="{ row }">
          <span v-if="row.remainingNum < 10" style="color: red; font-weight: bold">{{ row.remainingNum }}</span>
          <span v-else style="color: green; font-weight: 500">{{ row.remainingNum }}</span>
        </template>
        <template #reduceHandler="{ row }">
          <div v-if="row.remainderCount > 0" style="display: flex; align-items: center">
            <t-input v-model="row.reduceCount" size="small" type="number" suffix="次" min="1" style="width: 80px" />
            <t-button
              theme="danger"
              variant="outline"
              size="small"
              style="margin-left: 5px"
              @click="handleClickReduce(row)"
            >
              扣减
            </t-button>
          </div>
        </template>
        <template #op="{ row }">
          <t-space>
            <t-link theme="primary" @click="handleClickDetail(row)">{{ $t('pages.listBase.detail') }}</t-link>
            <t-link v-if="row.level === 1" theme="primary" @click="handleClickTopUp(row)">充值</t-link>
          </t-space>
        </template>
      </t-table>
      <t-dialog
        v-model:visible="topUpConfirmVisible"
        :header="topupTitle"
        :on-cancel="onCancelTopUp"
        @confirm="onConfirmTopUp"
      >
        <template #body>
          <div class="dialog-info-block" style="display: flex; justify-content: space-between">
            <t-input
              v-model="topupNum"
              label="充值次数："
              type="number"
              suffix="次"
              placeholder="请输入充值次数"
              style="width: 240px"
            />
            <t-input
              v-model="topupMoney"
              label="充值金额："
              type="number"
              suffix="元"
              placeholder="请输入充值金额"
              style="width: 240px"
            />
          </div>
        </template>
      </t-dialog>

      <t-dialog
        v-model:visible="addUserConfirmVisible"
        :header="`新增${sessionType === 1 ? '晨练' : sessionType === 2 ? '午场' : '晚场'}会员卡`"
        :on-cancel="onCancelAdd"
        width="590px"
        @confirm="onConfirmAdd"
      >
        <template #body>
          <div class="dialog-info-block" style="display: flex; justify-content: space-between">
            <t-input v-model="addUserName" label="姓名：" placeholder="请输入姓名" style="width: 240px" />
            <t-input v-model="addUserPhone" label="手机号：" placeholder="请输入手机号" style="width: 240px" />
          </div>
          <div class="dialog-info-block" style="display: flex; justify-content: space-between; margin-top: 10px">
            <t-input
              v-model="addPayCount"
              label="充值次数："
              type="number"
              suffix="次"
              placeholder="请输入充值次数"
              style="width: 240px"
            />
            <t-input
              v-model="addPayMoney"
              label="充值金额："
              type="number"
              suffix="元"
              placeholder="请输入充值金额"
              style="width: 240px"
            />
          </div>
        </template>
      </t-dialog>

      <t-dialog
        v-model:visible="addTempUserConfirmVisible"
        width="590px"
        :header="`新增${sessionType === 1 ? '晨练' : sessionType === 2 ? '午场' : '晚场'}临时卡`"
        @confirm="onConfirmAddTemp"
      >
        <template #body>
          <t-radio-group v-model="tempCardType" default-value="0">
            <t-radio value="0">线下缴费</t-radio>
            <t-radio value="2">美团缴费</t-radio>
          </t-radio-group>
          <div class="dialog-info-block" style="display: flex; justify-content: space-between; margin-top: 10px">
            <t-input
              v-model="addTempPayCount"
              label="充值次数："
              type="number"
              suffix="次"
              placeholder="请输入充值次数"
              style="width: 240px"
            />
            <t-input
              v-model="addTempPayMoney"
              label="充值金额："
              type="number"
              suffix="元"
              placeholder="请输入充值金额"
              style="width: 240px"
            />
          </div>
          <div class="dialog-info-block" style="display: flex; justify-content: space-between; margin-top: 10px">
            <t-input v-model="addTempUserName" label="姓名：" placeholder="请输入姓名" style="width: 240px" />
          </div>
        </template>
      </t-dialog>

      <t-dialog
        v-model:visible="showImportDialog"
        width="720px"
        :header="`导入数据`"
        confirm-btn="确认导入"
        :confirm-loading="importLoading"
        @confirm="onConfirmImportCards"
      >
        <template #body>
          <t-steps layout="vertical" :current="currentImportStep">
            <t-step-item title="下载模板" content='点击"下载"按钮下载需要导入的模板文件'>
              <template #extra>
                <t-button size="medium" variant="base" @click="downloadTemplate"> 下载 </t-button>
              </template>
            </t-step-item>
            <t-step-item title="上传文件" content="完成文件填写后，点击上传文件">
              <template #extra>
                <t-upload
                  v-model="files"
                  :auto-upload="autoUpload"
                  :allow-upload-duplicate-file="true"
                  :theme="display"
                  :data="{ extra_data: 123, file_name: 'certificate' }"
                  :abridge-name="[10, 8]"
                  :format-response="formatResponse"
                  draggable
                  action="https://mini.ydmaster.top/manager/user/import/check"
                />
              </template>
            </t-step-item>
            <t-step-item title="校验数据" content="上传完成后，校验数据是否正确，校验成功即可确认导入">
              <template v-if="uploadResult.code !== -1" #extra>
                <t-alert :theme="uploadResult.code === 0 ? 'success' : 'error'">
                  <p>上传结果：{{ uploadResult.message }}</p>
                  <p style="font-size: 12px" v-for="(item, index) in uploadResult.data" :key="index">{{ item }}</p>
                </t-alert>
              </template>
            </t-step-item>
          </t-steps>
        </template>
      </t-dialog>
    </div>
  </div>
</template>
<script setup lang="ts">
import { AddIcon, ChevronRightDoubleIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin, PageInfo, PrimaryTableCol, TableRowData, UploadProps } from 'tdesign-vue-next';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import {
  addMemberUser,
  addTempMemberUser,
  getMemberList,
  getUserTodaySummary,
  UserConsumer,
  userPay,
  UserImportInit,
  UserExportExport,
} from '@/api/member';
import { AddUserParams, UserConsumerParams, UserPayParams, UserTodaySummaryData } from '@/api/model/memberModel';
import { prefix } from '@/config/global';
import { t } from '@/locales';
import { useSettingStore } from '@/store';

const store = useSettingStore();
const router = useRouter();

const USECOUNT_STATUS_OPTIONS = [
  { value: '0', label: '达到1次' },
  { value: '4', label: '达到5次' },
  { value: '9', label: '达到10次' },
  { value: '19', label: '达到20次' },
  { value: '29', label: '达到30次' },
  { value: '39', label: '达到40次' },
  { value: '49', label: '达到50次' },
];
const USERLEVEL_OPTIONS = [
  { value: '1', label: '会员' },
  { value: '0', label: '线下缴费' },
  { value: '2', label: '美团缴费' },
];
const TODAYDEDUCTION_STATUS_OPTIONS = [
  { value: 1, label: '已消减' },
  { value: 0, label: '未消减' },
];

const COLUMNS: PrimaryTableCol[] = [
  {
    title: '序号',
    fixed: 'left',
    width: 60,
    ellipsis: true,
    align: 'left',
    colKey: 'serial-number',
  },
  {
    title: '姓名',
    fixed: 'left',
    width: 120,
    ellipsis: true,
    align: 'left',
    colKey: 'userName',
  },
  { title: '手机号', colKey: 'mobilePhone', width: 160 },
  {
    title: '充值次数',
    width: 100,
    ellipsis: true,
    colKey: 'payCount',
  },
  {
    title: '剩余次数',
    width: 100,
    ellipsis: true,
    colKey: 'remainderCount',
  },
  {
    title: '当日划卡次数',
    width: 120,
    ellipsis: true,
    colKey: 'todayUseCount',
  },
  {
    title: '消减操作',
    width: 200,
    ellipsis: true,
    colKey: 'reduceHandler',
  },
  {
    title: '最近充值日期',
    width: 200,
    ellipsis: true,
    colKey: 'lastPayTime',
  },
  // {
  //   title: '加入时间',
  //   width: 200,
  //   ellipsis: true,
  //   colKey: 'registerTime',
  // },
  {
    align: 'left',
    fixed: 'right',
    width: 120,
    colKey: 'op',
    title: t('components.commonTable.operation'),
  },
];

const formData = ref({
  userName: '',
  mobilePhone: '',
  gtConsumerCount: '',
  todayConsumer: '',
  level: '1',
});

const rowKey = 'index';
const verticalAlign = 'top' as const;

interface PagenationDTO {
  defaultPageSize?: number;
  total: number;
  defaultCurrent?: number;
  current: number;
  page: number;
  pageSize?: number;
}
const pagination = ref<PagenationDTO>({
  defaultPageSize: 50,
  total: 100,
  defaultCurrent: 1,
  current: 1,
  page: 1,
  pageSize: 50,
});

const data = ref([]);

const dataLoading = ref(false);
const fetchData = async () => {
  dataLoading.value = true;
  try {
    const res = await getMemberList({
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      cardType: sessionType.value,
      ...formData.value,
    });
    if (res.code === 0) {
      res.data.userList.map((item: { reduceCount: number }) => {
        item.reduceCount = 1;
        return item;
      });
      data.value = res.data.userList;
      pagination.value = {
        ...pagination.value,
        total: res.data.totalCount,
      };
    }
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

const todaySummaryData = ref<UserTodaySummaryData>(null);
const fetchUserTodaySummary = async () => {
  const res = await getUserTodaySummary();
  if (res.code === 0) {
    todaySummaryData.value = res.data;
  }
};

const handleClickReduce = async (row: any) => {
  console.log(row);
  const userConsumerParams: UserConsumerParams = {
    cardId: row.cardId,
    useCount: row.reduceCount,
  };
  const res = await UserConsumer(userConsumerParams);
  if (res.code === 0) {
    fetchData();
    fetchUserTodaySummary();
    MessagePlugin.success(res.message);
  }
};

const topupTitle = ref<string>('充值操作：');
const topUpConfirmVisible = ref(false);
const curRowInfo = ref(null);
const topupNum = ref<number>(0);
const topupMoney = ref<number>(0);
const handleClickTopUp = (row: any) => {
  topUpConfirmVisible.value = true;
  curRowInfo.value = row;
  topupTitle.value = `充值操作：（${row.userName}-${row.mobilePhone}）`;
  topupNum.value = 35;
  topupMoney.value = 400;
};
const onConfirmTopUp = async () => {
  const params: UserPayParams = {
    cardId: curRowInfo.value.cardId,
    payCount: topupNum.value,
    payMoney: topupMoney.value,
  };
  const res = await userPay(params);
  if (res.code === 0) {
    topUpConfirmVisible.value = false;
    fetchData();
    MessagePlugin.success(res.message);
  }
};

const onCancelTopUp = () => {
  resetRow();
};

const resetRow = () => {
  topupTitle.value = '充值操作：';
  curRowInfo.value = null;
  topupNum.value = 35;
  topupMoney.value = 400;
};

const onSessionTypeChanged = () => {
  onReset();
};

const addUserConfirmVisible = ref(false);
const addUserName = ref<string>('');
const addUserPhone = ref<string>('');
const addPayCount = ref<number>(35);
const addPayMoney = ref<number>(400);

const onCancelAdd = () => {
  addUserName.value = null;
  addUserPhone.value = null;
};
const handleClickAddUser = () => {
  addUserConfirmVisible.value = true;
  addUserName.value = null;
  addUserPhone.value = null;
};

const sessionType = ref<number>(1); // 场次类型 1-晨练 2-午场 3-晚场
const onConfirmAdd = async () => {
  const user: AddUserParams = {
    mobilePhone: addUserPhone.value,
    userName: addUserName.value,
    payCount: addPayCount.value,
    payMoney: addPayMoney.value,
    cardType: sessionType.value,
  };
  if (!addUserPhone.value || !addUserName.value) {
    MessagePlugin.warning('请填写要新增会员的姓名和手机号~');
    return;
  }
  const res = await addMemberUser(user);
  MessagePlugin.success(res.message);
  if (res.code === 0) {
    addUserConfirmVisible.value = false;
    fetchData();
  }
};

const addTempUserConfirmVisible = ref(false);
const addTempPayCount = ref<number>(1);
const addTempPayMoney = ref<number>(10);
const addTempUserName = ref<string>('');
const tempCardType = ref<string>('0'); // 临时卡类型，0-线下 2-美团
const handleClickAddTempUser = () => {
  addTempUserConfirmVisible.value = true;
};

const onConfirmAddTemp = async () => {
  const user: AddUserParams = {
    payCount: addTempPayCount.value,
    payMoney: addTempPayMoney.value,
    level: Number(tempCardType.value),
    userName: addTempUserName.value,
    cardType: sessionType.value,
  };
  const res = await addTempMemberUser(user);
  MessagePlugin.success(res.message);
  if (res.code === 0) {
    addTempUserConfirmVisible.value = false;
    fetchData();
  }
};

onMounted(() => {
  fetchData();
  fetchUserTodaySummary();
});

const onReset = () => {
  formData.value = {
    userName: '',
    mobilePhone: '',
    gtConsumerCount: '',
    todayConsumer: '',
    level: '1',
  };
  pagination.value = {
    defaultPageSize: 50,
    total: 50,
    defaultCurrent: 1,
    current: 1,
    page: 1,
    pageSize: 50,
  };
  fetchData();
};

const handleClickDetail = (row: any) => {
  router.push(`/member/detail/${row.cardId}`);
};

const go2CardTypeDetail = (sessionType: number) => {
  router.push(`/member/usedetail/${sessionType}`);
};

const onSubmit = () => {
  pagination.value = {
    defaultCurrent: 1,
    current: 1,
    page: 1,
    total: 0,
    pageSize: 50,
  };
  fetchData();
};
const rehandlePageChange = (pageInfo: PageInfo, newDataSource: TableRowData[]) => {
  console.log('分页变化', pageInfo, newDataSource);
  pagination.value = {
    ...pagination.value,
    page: pageInfo.current,
    current: pageInfo.current,
    pageSize: pageInfo.pageSize,
  };
  fetchData();
};
const rehandleChange = (changeParams: unknown, triggerAndData: unknown) => {
  console.log('统一Change', changeParams, triggerAndData);
};

const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any, // TO BE FIXED
);

const showImportDialog = ref(false);
const currentImportStep = ref(1);

function getCurrentDate(needTime = false) {
  const d = new Date();
  let month = d.getMonth() + 1;
  month = month < 10 ? Number(`0${month}`) : month;
  const date = `${d.getFullYear()}-${month}-${d.getDate()}`;
  const time = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
  if (needTime) return [date, time].join(' ');
  return date;
}
const autoUpload = ref(true);
const files = ref<UploadProps['value']>([]);
const display = ref<UploadProps['theme']>('file');

const downloadTemplate = () => {
  const getTimestamp = new Date().getTime();
  window.location.href = `https://ydzg-static.oss-cn-beijing.aliyuncs.com/admin-pro/%E7%94%A8%E6%88%B7%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx?timestamp=${getTimestamp}`;
};
interface UploadResult {
  code: number;
  message: string;
  uploadTime?: string;
  data?: string;
}
const uploadResult = ref<UploadResult>({
  code: -1,
  message: '',
});
// res.url 图片地址；res.uploadTime 文件上传时间；res.error 上传失败的原因
function formatResponse(res: any) {
  // 响应结果添加上传时间字段，用于 UI 显示
  res.uploadTime = getCurrentDate();
  currentImportStep.value = 3;
  uploadResult.value = res as UploadResult;
  return res;
}

const importLoading = ref(false);
const onConfirmImportCards = () => {
  if (uploadResult.value?.code === 0) {
    importLoading.value = true;
    // 可以导入
    UserImportInit({
      excelName: uploadResult.value.data,
    })
      .then((res) => {
        if (res.code === 0) {
          fetchData();
          showImportDialog.value = false;
          MessagePlugin.success('导入成功');
        } else {
          MessagePlugin.success(res.message);
        }
      })
      .finally(() => {
        importLoading.value = false;
      });
  } else {
    MessagePlugin.warning(uploadResult.value.message);
  }
};

const exportHandleClick = () => {
  window.open(location.origin + '/manager/user/export');
  // UserExportExport({
  //   month: '',
  // })
  //   .then((res) => {
  //     if (res.code === 0) {
  //       MessagePlugin.success('导出成功');
  //       const url = window.URL.createObjectURL(new Blob([res.data]));
  //       const link = document.createElement('a');
  //       link.href = url;
  //       link.setAttribute('download', 'filename.xlsx'); // 设置下载的文件名
  //       document.body.appendChild(link);
  //       link.click();
  //       document.body.removeChild(link);
  //       window.URL.revokeObjectURL(url);

  //     } else {
  //       MessagePlugin.success(res.message);
  //     }
  //   })
  //   .finally(() => {});
};
</script>

<style lang="less" scoped>
.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);
  border-radius: var(--td-radius-medium);

  .table-container {
    margin-top: var(--td-comp-margin-xxl);
  }
}

.form-item-content {
  width: 100%;
}

.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .expand {
    .t-button__text {
      display: flex;
      align-items: center;
    }
  }
}

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: var(--td-comp-margin-s);
  }
}

.right-handlers-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
.user-tabs {
  margin: 10px 0;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

:deep(.t-table__pagination-wrap) {
  position: sticky;
  bottom: 0;
  background: #fff;
  z-index: 99;
  border-top: 1px solid #ddd;
}
</style>
